<template>
  <div class="loginPanel">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>用户登录</span>
      </div>
      <div>
        <el-form ref="form" :model="loginForm" :rules="rules" label-width="0">
          <el-form-item prop="userName">
            <el-input @keyup.enter.native="$refs.password.focus()" prefix-icon="el-icon-user" placeholder="请输入用户名" v-model="loginForm.userName" :clearable="true"/>
          </el-form-item>
          <el-form-item prop="password">
            <el-input ref="password" @keyup.enter.native="onSubmit" prefix-icon="el-icon-lock" placeholder="请输入密码" v-model="loginForm.password" type="password"
                      :show-password="true"/>
          </el-form-item>
          <el-form-item align="center">
            <el-button type="primary" style="width:100%;" :loading="loading" @click="onSubmit">登录</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
  export default {
    name: "login",
    data() {
      return {
        loading: false,
        result: '',
        loginForm: {
          userName: '',
          password: ''
        },
        rules: {
          userName: [
            {required: true, message: '请输入用户名', trigger: 'blur'},
            {min: 5, max: 20, message: '长度5到20个字符', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {min: 5, max: 20, message: '长度5到20个字符', trigger: 'blur'}
          ]
        }
      }
    },
    mounted() {
      if (this.result !== '') {
        this.$message.error(this.result);
      }
    },
    methods: {
      onSubmit() {
        this.$refs.form.validate(valid => {
          if (valid) {
            this.loading = true;
            this.$store.dispatch('login', this.loginForm).then(async () => {
              this.loading = false;
              await this.$router.push({path: '/'});
            }).catch(() => {
              this.loading = false;
            });
          }
        })
      }
    }
  }
</script>

<style scoped>
  .loginPanel {
    margin: 0;
    padding: 0;
    height: 100%;
    width: 100%;
    background: url("/static/images/login_bg.jpg") no-repeat center center;
  }

  .box-card {
    width: 400px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -240px;
    margin-top: -143px;
  }
</style>
